package com.yunzong.wifi.netconfig.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

public class UDPMultiClient {
    private MulticastSocket udpSocket;
    private boolean isClose;
    private static final int PORT = 9999;
    private static final String GROUP_IP = "239.0.0.1";
    private static final int TTL = 2; //最大路由传递量

    public UDPMultiClient() {
        try {
            this.udpSocket = new MulticastSocket(PORT);
            InetAddress group = InetAddress.getByName(GROUP_IP);
            this.udpSocket.joinGroup(group);
            this.udpSocket.setTimeToLive(TTL);
            this.isClose = false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized void close() {
        if (!this.isClose) {
            this.udpSocket.close();
            this.isClose = true;
        }
    }

    protected void finallize() throws Throwable {
        close();
        super.finalize();
    }

    /**
     * 发送数据
     * @param data
     * @param ip
     */
    public void send(byte[] data, String ip) {
        try {
            DatagramPacket datagramPacket = new DatagramPacket(data, data.length, InetAddress.getByName(ip), PORT);
            this.udpSocket.send(datagramPacket);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
